package com.qdxwx.manage.controller.picture;

import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.common.config.UploadConfig;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.upload.UploadUtils;
import com.qdxwx.common.utils.FileUtils;
import com.qdxwx.common.utils.ImageUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.member.MemberTypeService;
import com.qdxwx.data.service.picture.PictureAlbumService;
import com.qdxwx.data.service.picture.PictureService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.picture.Picture;
import com.qdxwx.models.picture.PictureAlbum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import jakarta.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * 图片Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/picture")
public class PictureEditController extends BaseController {

    @Autowired
    private PictureService pictureService;
    @Autowired
    private WebsiteProfileService websiteProfileService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private MemberTypeService memberTypeService;
    @Autowired
    private PictureAlbumService pictureAlbumService;

    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error404;
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (channelId < 1) {
            channelId = 10;
        }
        mmap.put("channelId", channelId);
        mmap.put("memberTypes", memberTypeService.getList());
        return "picture/picture-add";
    }

    @PostMapping("/add.json")
    @Permissions("picture:edit")
    @Log(title = "上传图片", businessType = BusinessType.INSERT)
    @ResponseBody
    public AjaxResult addJson(HttpServletRequest request) throws IOException {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error("未登录，禁止操作");

        String title = TKString.trim(request.getParameter("title"));
        if (TKString.isEmpty(title)) return error("名称不能为空");
        String badWord = websiteProfileService.checkBadWord(title);
        if (badWord != null) {
            return error("标题含有敏感词‘" + badWord + "’，请修改后重新提交！");
        }
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) {
            return error("请选择所属分类");
        }
        Category category = categoryService.get(categoryId);
        if (category == null) {
            return error("找不到指定分类");
        }

        int levelId = TKConvert.toInteger(request.getParameter("levelId"));
        int price = TKConvert.toBigDecimal(request.getParameter("price")).multiply(BigDecimal.valueOf(100)).intValue();
        int isElite = TKConvert.toInteger(request.getParameter("isElite"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"));
        String intro = TKString.trim(request.getParameter("intro"));
        int createAlbum = TKConvert.toInteger(request.getParameter("createAlbum"));
        int albumId = 0;
        if (createAlbum == 1) {
            PictureAlbum album = new PictureAlbum();
            album.setTitle(title);
            album.setIntro(intro);
            album.setChannelId(category.getChannelId());
            album.setCategoryId(category.getCategoryId());
            album.setCategoryName(category.getCategoryName());
            album.setSubjectId(category.getSubjectId());
            album.setIsElite(isElite);
            album.setIsTop(isTop);
            album.setUserId(manager.getUserId());
            album.setUserName(manager.getManagerName());
            album.setStatus(1);
            pictureAlbumService.insert(album);
            albumId = album.getId();
        }
        String pictureStr = TKString.trim(request.getParameter("pictures"));
        if (pictureStr.length() < 1) {
            return error("请先上传图片！");
        }
        String[] pathArray = pictureStr.split(",");
        //logger.info(Arrays.toString(pathArray));
        int count = 0;
        for (String picPath : pathArray) {
            Picture picture = new Picture();
            if (count > 0) {
                picture.setTitle(title + count);
            } else {
                picture.setTitle(title);
            }
            picture.setChannelId(category.getChannelId());
            picture.setCategoryId(category.getCategoryId());
            picture.setCategoryName(category.getCategoryName());
            picture.setSubjectId(category.getSubjectId());
            picture.setLevelId(levelId);
            picture.setPrice(price);
            picture.setIsElite(isElite);
            picture.setIsTop(isTop);
            picture.setDownCount(0);
            picture.setViewCount(0);
            picture.setImgUrl(picPath);
            //原图
            String oldPath = picture.getImgUrl();
            String fileExt = UploadUtils.getFileExt(oldPath);
            //如果是临时文件夹
            if (oldPath.contains("/temps/")) {
                //原图图地址
                String imgUrl = UploadUtils.getSavePath(UploadConfig.uploadImageFolder, fileExt);
                if (!FileUtils.copyFile(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + imgUrl)) {
                    logger.error("文件上传失败：" + picPath);
                    continue;
                }
                picture.setImgUrl(imgUrl);
            }
            //读取原图
            File srcFile = new File(UploadConfig.uploadRoot + oldPath);
            BufferedImage srcImage = ImageIO.read(srcFile);
            if (srcImage == null) {
                logger.error("该文件不是图片：" + picPath);
                continue;
            }
            picture.setFileSize(srcFile.length());
            picture.setFileExt(fileExt);
            picture.setImgWidth(srcImage.getWidth());
            picture.setImgHeight(srcImage.getHeight());
            picture.setImgDpi(0);
            picture.setUserId(manager.getUserId());
            picture.setUserName(manager.getManagerName());
            picture.setStatus(1);
            //预览图地址
            String viewPath = UploadUtils.getSavePath(UploadConfig.uploadPreviewFolder, "jpg");
            //水印图片地址

            BufferedImage srcWater = ImageIO.read(new File(UploadConfig.uploadRoot + "/logo-water.png"));

            ImageUtils.press(srcImage, UploadConfig.uploadRoot + viewPath, srcWater, 0.5f);
            picture.setViewUrl(viewPath);
            //封面图地址
            String coverPath = UploadUtils.getSavePath(UploadConfig.uploadCoverFolder, "jpg");
            ImageUtils.zoomWithCut(srcImage, UploadConfig.uploadRoot + coverPath, 500, 350);
            picture.setCoverUrl(coverPath);
            count += pictureService.insert(picture);
            if (albumId > 0 && picture.getId() > 0) {
                pictureAlbumService.insertItem(albumId, picture.getId());
            }
        }
        if (count > 0) {
            return AjaxResult.success("上传成功，本次共上传（" + count + "）张图片！");
        } else {
            return AjaxResult.error();
        }
    }

    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request, ModelMap mmap) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error404;
        Picture picture = pictureService.get(id);
        if (picture == null) return error500;
        mmap.put("picture", picture);
        mmap.put("memberTypes", memberTypeService.getList());
        return "picture/picture-edit";
    }

    @PostMapping("/save.json")
    @Permissions("picture:edit")
    @Log(title = "图片操作", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult saveEdit(HttpServletRequest request) throws IOException {
        Manager manager = SessionUtils.getManager();
        if (manager == null) return error("未登录，禁止操作");
        int id = TKConvert.toInteger(request.getParameter("id"));
        Picture picture = pictureService.get(id);
        if (picture == null) {
            return error("找不到id为:" + id + "的图集");
        }
        String title = request.getParameter("title");
        if (TKString.isEmpty(title)) return error("名称不能为空");
        String badWord = websiteProfileService.checkBadWord(title);
        if (badWord != null) {
            return error("标题含有敏感词‘" + badWord + "’，请修改后重新提交！");
        }
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) return error("请选择分类");
        Category category = categoryService.get(categoryId);
        if (category == null) return error("找不到指定分类");
        String imgUrl = TKString.trim(request.getParameter("imgUrl"));
        if (TKString.isEmpty(imgUrl)) return error("请先上传图片");
        String viewUrl = TKString.trim(request.getParameter("viewUrl"));
        String coverUrl = TKString.trim(request.getParameter("coverUrl"));

        picture.setTitle(title);
        picture.setChannelId(category.getChannelId());
        picture.setSubjectId(category.getSubjectId());
        picture.setCategoryId(category.getCategoryId());
        picture.setCategoryName(category.getCategoryName());
        picture.setLevelId(TKConvert.toInteger(request.getParameter("levelId")));
        picture.setPrice(TKConvert.toBigDecimal(request.getParameter("price")).multiply(BigDecimal.valueOf(100)).intValue());
        picture.setImgUrl(imgUrl);
        picture.setViewUrl(viewUrl);
        picture.setCoverUrl(coverUrl);
        picture.setIsElite(TKConvert.toInteger(request.getParameter("isElite"), 0));
        picture.setIsTop(TKConvert.toInteger(request.getParameter("isTop"), 0));
        picture.setDownCount(TKConvert.toInteger(request.getParameter("downCount"), 0));
        picture.setViewCount(TKConvert.toInteger(request.getParameter("viewCount"), 0));
        //原图
        String oldPath = picture.getImgUrl();
        String fileExt = UploadUtils.getFileExt(oldPath);
        //如果是临时文件夹
        if (oldPath.contains("/temps/")) {
            //原图图地址
            String imgPath = UploadUtils.getSavePath(UploadConfig.uploadImageFolder, fileExt);
            if (!FileUtils.copyFile(UploadConfig.uploadRoot + oldPath, UploadConfig.uploadRoot + imgPath)) {
                logger.error("文件上传失败：" + oldPath);
                return AjaxResult.error("文件上传失败：" + oldPath);
            }
            picture.setImgUrl(imgPath);
        }
        //读取原图
        File srcFile = new File(UploadConfig.uploadRoot + oldPath);
        BufferedImage srcImage = ImageIO.read(srcFile);
        if (srcImage == null) {
            logger.error("该文件不是图片：" + oldPath);
            return AjaxResult.error("该文件不是图片：" + oldPath);
        }
        picture.setFileSize(srcFile.length());
        picture.setImgWidth(srcImage.getWidth());
        picture.setImgHeight(srcImage.getHeight());
        picture.setFileExt(fileExt);
        picture.setImgDpi(0);
        //预览图地址
        if (picture.getViewUrl().length() < 1) {
            String viewPath = UploadUtils.getSavePath(UploadConfig.uploadPreviewFolder, fileExt);
            //水印图片地址
            BufferedImage srcWater = ImageIO.read(new File(UploadConfig.uploadRoot + "/logo-water.png"));
            ImageUtils.press(srcImage, UploadConfig.uploadRoot + viewPath, srcWater, 0.5f);
            picture.setViewUrl(viewPath);
        }
        //封面图地址
        if (picture.getCoverUrl().length() < 1) {
            String coverPath = UploadUtils.getSavePath(UploadConfig.uploadCoverFolder, fileExt);
            ImageUtils.zoomWithCut(srcImage, UploadConfig.uploadRoot + coverPath, 500, 350);
            picture.setCoverUrl(coverPath);
        }
        int row = pictureService.update(picture);
        return toAjax(row);
    }


    /**
     * 上下架
     */
    @PostMapping("/update/status.json")
    @Log(title = "修改图片状态", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult UpdateStatus(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int status = TKConvert.toInteger(request.getParameter("status"), 0);
        if (id < 1 || status > 1 || status < -1) return error("参数异常");
        Picture picture = pictureService.get(id);
        if (picture == null) return error("未找到指定id图片，id=" + id);
        picture.setStatus(status);
        return toAjax(pictureService.update(picture));
    }

    /**
     * 固顶操作
     */
    @PostMapping("/update/top.json")
    @Log(title = "修改图片固顶", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult top(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isTop = TKConvert.toInteger(request.getParameter("isTop"), 0);
        if (id < 1 || isTop > 1 || isTop < 0) return error("参数异常");
        Picture picture = pictureService.get(id);
        if (picture == null) return error("未找到指定id图集，id=" + id);
        picture.setIsTop(isTop);
        return toAjax(pictureService.update(picture));
    }

    /**
     * 推荐操作
     */
    @PostMapping("/update/elite.json")
    @Log(title = "修改图片推荐", businessType = BusinessType.UPDATE)
    @ResponseBody
    public AjaxResult elite(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        int isElite = TKConvert.toInteger(request.getParameter("isElite"), 0);
        if (id < 1 || isElite > 1 || isElite < 0) return error("参数异常");
        Picture picture = pictureService.get(id);
        if (picture == null) return error("未找到指定id图集，id=" + id);
        picture.setIsElite(isElite);
        return toAjax(pictureService.update(picture));
    }

    @Permissions("picture:remove")
    @Log(title = "删除图片", businessType = BusinessType.DELETE)
    @PostMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        int id = TKConvert.toInteger(request.getParameter("id"));
        if (id < 1) return error("参数异常，id=" + id);
        Picture picture = pictureService.get(id);
        if (picture == null) return error("找不到指定id数据,id=" + id);
        if (picture.getStatus() == 1) return error("上架图片不能删除");
        int row = pictureService.deleteById(picture.getId());
        if (row > 0) {
            //删除专辑关联表
            pictureAlbumService.deleteItemByPictureId(picture.getId());
            //同步删除图片文件
            FileUtils.deleteFile(UploadConfig.uploadRoot + picture.getCoverUrl());
            FileUtils.deleteFile(UploadConfig.uploadRoot + picture.getViewUrl());
            FileUtils.deleteFile(UploadConfig.uploadRoot + picture.getImgUrl());
        }
        return toAjax(row);
    }
}
